from django.db import models

from ._base import BaseORM
from .role import Role
from service.encrypt import md5
from django.conf import settings


class User(BaseORM):
    gender_choice = (
        (1, '男'),
        (2, '女'),
        (3, '保密'),
    )
    nickname = models.CharField(verbose_name="昵称", max_length=128)
    username = models.CharField(verbose_name="用户名", max_length=128)
    password_hash = models.CharField(verbose_name="登录密码", max_length=255)
    mobile = models.CharField(verbose_name="手机", max_length=11)
    email = models.CharField(verbose_name="邮箱", max_length=64)
    avatar = models.TextField(verbose_name="头像地址", blank=True, null=True, default=settings.DEFAULT_AVATAR)
    postion = models.CharField(verbose_name="职位", max_length=64)
    gender = models.IntegerField(choices=gender_choice, default=3)

    is_enabled = models.BooleanField(verbose_name="账号是否可用 0-禁用 1-可用", default=True)
    # 其实部门不应该加null=True, blank=True, 因为按照通常的逻辑, 部门应该先于用户存在, 这里设置可为空, 避免我们往后从excel表中导入数据时报错
    # 而且我们设置了on_delete=models.SET_NULL, 意味着必须可为空
    department = models.ForeignKey(verbose_name="所属部门id", to='Department', on_delete=models.SET_NULL, null=True, blank=True)
    is_super = models.BooleanField(verbose_name="是否是超级管理员", default=False)
    sign = models.CharField(verbose_name="个性签名", max_length=255, blank=True, null=True)

    role_list = models.ManyToManyField(verbose_name='拥有的所有角色', to=Role, blank=True, db_table='ums_user_role')

    class Meta:
        db_table = 'ums_user'

    @property
    def password(self):
        return self.password_hash

    @password.setter
    def password(self, password):
        self.password_hash = md5(password)

    def json(self):
        return {
            "id": self.id,
            "nickname": self.nickname,
            "username": self.username,
            "avatar": self.avatar if self.avatar else settings.DEFAULT_AVATAR,  # 在新增form表单里已经做了
            "mobile": self.mobile,
            "email": self.email,
            "gender": self.get_gender_display(),
            "department": self.department.name if self.department else None,
            "postion": self.postion,
            "create_datetime": self.create_datetime.strftime("%Y-%m-%d %H:%M:%S"),
            "update_datetime": self.update_datetime.strftime("%Y-%m-%d %H:%M:%S"),
            "is_enabled": self.is_enabled,
            "is_deleted": self.is_deleted,
        }
